package com.viking.util.ftp;


import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpMode;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
/**
 * @author Silence
 * @date 2023年 03月06日 19:21:38
 */
@Slf4j
public final class FtpServicesUtil {
    private static Boolean moveFileToTarget(String fileFullNameCurrent, String fileFullNameTarget) {
        boolean ismove = false;

        File oldName = new File(fileFullNameCurrent);
        if (!oldName.exists()) {
            return ismove;
        }

        if (oldName.isDirectory()) {
            return false;
        }

        File newName = new File(fileFullNameTarget);

        if (newName.isDirectory()) {
            return false;
        }

        String pfile = newName.getParent();
        File pdir = new File(pfile);

        if (!pdir.exists()) {
            pdir.mkdirs();
        }
        ismove = oldName.renameTo(newName);
        return ismove;
    }

    public static void FtpTransport(){
        Ftp ftp = new Ftp((String) FtpSettingUtil.getPropertyValue("host"),21,(String) FtpSettingUtil.getPropertyValue("user"),(String) FtpSettingUtil.getPropertyValue("password"));
        ftp.setMode(FtpMode.Passive);
        File folder = new File((String)FtpSettingUtil.getPropertyValue("uploadFolder"));
        File[] listOfFiles = folder.listFiles();
        for (File file : listOfFiles) {
            if (file.isFile()) {
                if (ftp.upload("", FileUtil.file((String)FtpSettingUtil.getPropertyValue("uploadFolder")+"\\"+file.getName()))){
                    String filePath = (String)FtpSettingUtil.getPropertyValue("uploadFolder")+"\\"+file.getName();
                    String filePathNew = (String)FtpSettingUtil.getPropertyValue("backupFolder")+"\\"+file.getName();
                    if (!moveFileToTarget(filePath, filePathNew)){
                        log.info("{} move fail",file.getName());
                    }
                } else {
                    log.info("{} transport fail",file.getName());
                }
            }
        }
    }

}
